﻿using System.IO;

using WeDonekRpc.HttpService.Helper;
using WeDonekRpc.HttpService.Interface;

namespace WeDonekRpc.HttpService
{
    public class PostFile : IUpFile
    {
        private readonly Stream _Stream = null;
        private readonly UpFileParam _File;
        internal PostFile(UpFileParam param, Stream stream)
        {
            this._File = param;
            this._Stream = stream;
            this.FileSize = stream.Length;
        }
        /// <summary>
        /// 文件大小
        /// </summary>
        public long FileSize { get; }
        /// <summary>
        /// 文件名
        /// </summary>
        public string FileName => this._File.FileName;
        /// <summary>
        /// 文件类型
        /// </summary>
        public string FileType => this._File.Name;
        /// <summary>
        /// 内容类型
        /// </summary>
        public string ContentType => this._File.ContentType;

        public string FileMd5 => this._File.FileMd5;

        public byte FileCs => this._File.FileCs;

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="savePath"></param>
        /// <returns></returns>
        public string SaveFile(string savePath)
        {
            string path = FileHelper.GetFileFullPath(savePath);
            this._SaveFile(path);
            return path;
        }

        private void _SaveFile(string path)
        {
            FileInfo file = new FileInfo(path);
            if (!file.Directory.Exists)
            {
                file.Directory.Create();
            }
            using (FileStream stream = file.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read))
            {
                stream.Position = 0;
                if (this._FileStream == null)
                {
                    this._Stream.CopyTo(stream);
                }
                else
                {
                    stream.Write(this._FileStream, 0, this._FileStream.Length);
                }
                stream.Flush();
            }
        }
        private byte[] _FileStream = null;
        public byte[] ReadStream()
        {
            if (this._FileStream != null)
            {
                return this._FileStream;
            }
            this._FileStream = new byte[this._Stream.Length];
            this._Stream.Position = 0;
            this._Stream.Read(this._FileStream, 0, this._FileStream.Length);
            return this._FileStream;
        }
        public long CopyStream(Stream stream, int offset)
        {
            stream.Position = offset;
            this._Stream.Position = 0;
            this._Stream.CopyTo(stream);
            return (int)this._Stream.Length;
        }

        public Stream GetStream()
        {
            this._Stream.Position = 0;
            return this._Stream;
        }


        public void Dispose()
        {
            this._Stream.Dispose();
        }
    }
}
